﻿using AntdUI;
using FastReport.RichTextParser;
using Modbus;
using Model;
using Newtonsoft.Json;
using PrintLabel.Model;
using PrintLabel.Tools;
using PrintLabel.View;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using 纺织贸易管理系统;

namespace PrintLabel
{
    public partial class Main : AntdUI.BaseForm
    {
        private Modbus.ComService comService=new Modbus.ComService ();
        private List<ChiDianTable> Defects = new List<ChiDianTable> ();
        private OrderTable orderTable = new OrderTable ();
        private OrderDetailTable orderDetailTable = new OrderDetailTable ();
       private Parameter param = new Parameter() { BaudRate = "9600", Database = "Textiletradedb", Server = "192.168.0.109,1433", Stopwatch = "德莱宝", ComNum = "Com1" };
        public Main()
        {
            InitializeComponent();
            label28.Text=string.Empty;
        }
      
        private void LoadRolls()
        {            
            table1.DataSource=dbContext.dbcontext.Queryable<JuanHaoTable >().Where(x=>x.MachineID==txtjitaihao.Text&&x.rq>=DateTime.Today).OrderByDescending(x=>x.ID).ToList();
        }
        private void Main_Load(object sender, EventArgs e)
        {
            ///检查是否需要更新
            Task.Run(() =>
            {
                Boolean isupdate = new CheckUpdate.CheckUpdate() { LocalPath = Application.StartupPath }.IsNeedUpdate();
                if (isupdate)
                {
                    MessageBox.Show("有新的版本需要更新！系统将关闭。");
                    Process.Start(Application.StartupPath + "\\Updater.exe");
                    KillSelf.Kill();
                }
            });
            CreateTable(table1);
            CreateTable(table2);
            CreateDefectTable();
          
            cmbDanwei.Text = "米";
            var filepath = Application.StartupPath + "//Setting.json";
           
            if (File.Exists(filepath))
            {
                string json = File.ReadAllText(filepath);
                 param = JsonConvert.DeserializeObject<Parameter >(json);
                dbContext.dbcontext = new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
                { 
                    ConnectionString=$"server={param.Server };uid=sa;pwd=Kc123456;database={param.Database }",
                    DbType=SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection=true ,
                    InitKeyType=SqlSugar.InitKeyType.Attribute
                });
                cmbCopies.Text = param.Copies.ToString ();
                txtjitaihao.Text = param.MachineID.ToString();
            }
            else
            {
                File.WriteAllText(filepath, JsonConvert.SerializeObject(param));
            }
            txtjitaihao.Text = param.MachineID.ToString ();
            try
            {
                cmbCom.Items.AddRange(ComService.获取所有端口().ToArray());
                cmbCom.Text = param.ComNum;
            }
            catch(Exception ex) 
            {
                ShowMessage.ShowErrorMessagebox(this, "获取COM口的时候发生了错误：" + ex.Message);
            }
            try
            {
                cmbmabiao.Items.AddRange(StopwatchSyle.StopwatchList.ToArray());
                cmbmabiao.Text= param.Stopwatch;
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "获取码表类型的时候发生了错误：" + ex.Message);
            }
            try
            {
                cmbLabels.Items.AddRange(Tools.ShippingmarkHelper.获取所有模板(System.Windows.Forms.Application.StartupPath+"\\Labels\\").ToArray());
                cmbLabels.Text = param.Shippingmark;
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "获取唛头模板的时候发生了错误：" + ex.Message);
            }
            cmbBoteli.Text = param.BaudRate;
            comService.Stopwatch = cmbmabiao.Text ;
            comService.BaudRate =cmbBoteli.Text.ObjToInt ();
            try
            {
                comService.打开端口(cmbCom.Text);
                timer1.Start();
            }
            catch(Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "打开串口的时候发生了错误：" + ex.Message);
            }
            ShippingmarkHelper.DownLoadShinppingmark(Application.StartupPath );
            LoadRolls();
            CreateCidianBtn();
        }
        private void CreateDefectTable()
        {
            table3.AutoSizeColumnsMode = AntdUI.ColumnsMode.Fill;
            table3.Columns = new AntdUI.ColumnCollection()
            {
                 new AntdUI.Column ("ChiDianName","疵点名称"),
                new AntdUI.Column ("WeiZhi","位置"),
                 new AntdUI.Column ("ShuLiang","长度"),
                 new AntdUI.Column ("KouFeng","扣分"),
                  new AntdUI.Column ("IsALL","通匹"),
                   new AntdUI.Column ("EdgeDistance","边距"),
            };
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                comService.发送数据();
                if (Regex.IsMatch(comService.数字, @"^[+-]?\d*[.]?\d*$"))
                {
                    cmbDanwei.Text = string.IsNullOrWhiteSpace(comService.GetUnite()) ? "米" : comService.GetUnite();
                    txtLength.Text = (double.Parse(comService.数字)).ToString("N2");
                }
            }
            catch (Exception ex) 
            { 
                timer1.Stop();
                switch1.Checked = false;
                ShowMessage.ShowErrorMessagebox(this,"读取码表的数字的时候发生了错误！"+ex.Message);
                
            }
        }

        private void switch1_CheckedChanged(object sender, bool value)
        {
            if (value) 
            {
                comService.打开端口(cmbCom.Text);
                timer1.Start();
            }
            else
            {
                timer1.Stop();
            }
        }
        private string CreateBarcode()
        {
            var danhao = "JH" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString();
            danhao += DateTime.Now.Second.ToString() + txtganghao.Text  + txtjuanhao.Text ;
            return danhao;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtStockname.Text))
                {
                    ShowMessage.ShowErrorMessagebox(this, "请选择一下仓库");
                    return;
                }
                if (txtLength.Text.ObjToDecimal() == 0)
                {
                    ShowMessage.ShowErrorMessagebox(this, "长度不能为0");
                    return;
                }
                if (string.IsNullOrEmpty(txtganghao.Text))
                {
                    ShowMessage.ShowErrorMessagebox(this, "缸号不能为空");
                    return;
                }
                if (string.IsNullOrEmpty(txtyanse.Text))
                {
                    ShowMessage.ShowErrorMessagebox(this, "颜色不能为空");
                    return;
                }
                if (string.IsNullOrEmpty(txtmenfu.Text))
                {
                    ShowMessage.ShowErrorMessagebox(this, "门幅不能为空");
                    return;
                }
                if (string.IsNullOrEmpty(txtDengji.Text))
                {
                    ShowMessage.ShowErrorMessagebox(this, "请选择一下等级");
                    return;
                }
                var roll = new JuanHaoTable()
                {
                    yanse = txtyanse.Text,
                    MaShu = txtguama.Value,
                    GangHao = txtganghao.Text,
                    SampleName = txtpingming.Text,
                    biaoqianmishu = Math.Round(txtLength.Text.ObjToDecimal() / txtguama.Text.ObjToDecimal() * 100) - txtzengsong.Text.ObjToDecimal(),
                    PiHao = txtjuanhao.Text.ObjToInt(),
                    rq = DateTime.Now,
                    JuanHao = CreateBarcode(),
                    MachineID = txtjitaihao.Text,
                    Danwei = cmbDanwei.Text,
                    JiaJian = txtzengsong.Text.ObjToDecimal(),
                    Ckmc = txtStockname.Text,
                    CustomerPingMing = txtCustomFricename.Text,
                    CustomerColorNum = txtCustomColor.Text,
                    SampleNum = txtBianhao.Text,
                    Hetonghao = txtHetonghao.Text,
                    DengJI = txtStockname.Text.Contains("次品") ? "C" : txtDengji.Text,
                    OrderNum = txtOrdernum.Text,
                    state = chkchengjian.Checked ? 0 : 1,
                    Kezhong = txtkezhong.Text,
                    Menfu = txtmenfu.Text,
                    kuanhao = txtKuanhao.Text,
                    MiShu = txtLength.Text.ObjToDecimal(),
                    CustomerName = orderTable.CustomerName,
                    Density = orderDetailTable.Density,
                    EnglishName = orderDetailTable.EnglishName,
                    SecondaryEncoding = orderDetailTable.SecondaryEncoding,
                    Saleman = orderTable.SaleMan,
                    Composition = orderDetailTable.Component,
                    guige = orderDetailTable.Specifications,
                    Huahao = orderDetailTable.Huahao,
                    Weight = orderDetailTable.weight.ObjToDecimal(),
                };
                foreach (var item in Defects)
                {
                    roll.Cidian += "{";
                    roll.Cidian += "疵点名称" + item.ChiDianName.Split('(')[0] + ",";
                    roll.Cidian += "位置" + item.WeiZhi + ",";
                    roll.Cidian += "长度" + item.ShuLiang.ToString("N2") + ",";
                    roll.Cidian += "扣分米" + item.KouFeng.ToString("N0") + ",";
                    roll.Cidian += "疵点备注" + item.BeiZhu + "'";
                    roll.Cidian += "}";
                }
                dbContext.dbcontext.BeginTran();
                if (checkbox2.Checked)
                { 
                    roll.PiHao = RollHelper.CreatGangJuanhao(roll);
                }
                dbContext.dbcontext.Insertable(roll).ExecuteCommand();
                if (Defects.Count > 0)
                {
                    Defects.ForEach(item => { item.JuanHao = roll.JuanHao; });
                    dbContext.dbcontext.Insertable(Defects).ExecuteCommand();
                }
                if (chkchengjian.Checked)
                {
                    RollHelper.CreateStock(roll);
                }
                dbContext.dbcontext.CommitTran();
                if (checkbox1.Checked)
                {
                    PrintLabel(PrintStyle.Print, roll);
                }
                txtjuanhao.Text =( txtjuanhao.Text.ObjToInt()+1).ToString ();
                txtzengsong.Text = "0";
                LoadRolls();
                Defects.Clear();
                table3.DataSource=Defects;
                CalFinishNums();
                
            }
            catch(Exception ex)
            {
                dbContext.dbcontext.RollbackTran();
                ShowMessage.ShowErrorMessagebox(this, "保存的时候发生了错误：" + ex.Message);
            }
        }
        /// <summary>
        /// 计算已经检验好的米数
        /// </summary>
        private void CalFinishNums()
        {
            var rolls = dbContext.dbcontext.Queryable<JuanHaoTable >().Where(x => x.OrderNum == txtOrdernum.Text && x.SampleNum  == txtBianhao.Text && x.kuanhao == txtKuanhao.Text
            && x.yanse == txtyanse.Text&&x.Ckmc=="仓库"&&x.state==0).ToList ();
            if(rolls!=null)
            {
                txtCheckNums.Text =rolls.Sum(x=>x.biaoqianmishu ).ToString ();
            }
        }
        private void PrintLabel(PrintStyle printStyle,JuanHaoTable roll)
        {
            try
            {
                var fs = new FastReport.Report();
                fs.Load(Application.StartupPath + "\\Labels\\" + cmbLabels.Text);
                fs.RegisterData(GetData(roll));
                switch (printStyle)
                {
                    case PrintStyle.Preview:
                        fs.Show();
                        break;
                    case PrintStyle.Design:
                        fs.Design();
                        break;
                    case PrintStyle.Print:
                        fs.PrintSettings.Printer = new PrinterSettings().PrinterName;
                        fs.PrintSettings.Copies = cmbCopies.Text.ObjToInt();
                        fs.PrintSettings.ShowDialog = false;
                        fs.Print();
                        break;
                }
            }
            catch (Exception ex)
            {
                ShowMessage.ShowErrorMessagebox(this, "打印票签的时候发生了错误！" + ex.Message);
            }
        }
        private DataSet GetData(JuanHaoTable roll)
        {
            var dt = ShippingMark.CreateShippingDatatable(roll, 1, 1,string.Empty);
            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(dt);
            return dataSet;
        } 
        private void CreateTable(AntdUI.Table table)
        {
            table.AutoSizeColumnsMode= ColumnsMode.Fill;
            table.Columns=new ColumnCollection ();
            table.Columns.AddRange ( new AntdUI.Column[] {
                new AntdUI.Column("rq","打卷日期"){ Fixed=true},
                new AntdUI.Column("OrderNum","订单号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("SampleName","品名",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("GangHao","缸号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("yanse","颜色"),
                new AntdUI.Column("kuanhao","款号"),
                new AntdUI.Column("PiHao","匹号"),
                new AntdUI.Column("MaShu","挂码"),
                 new AntdUI.Column("biaoqianmishu","票签长度"){ Fixed=true},
                 new AntdUI.Column("JiaJian","赠送"){ Fixed=true},
                 new AntdUI.Column("Danwei","单位"){ Fixed=true},
                new AntdUI.Column("JuanHao","条码"){ Fixed=true},
            });
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            param.BaudRate = cmbBoteli.Text;
            param.ComNum = cmbCom.Text;
            param.Stopwatch = cmbmabiao.Text;
            param.Shippingmark = cmbLabels.Text;
            param.Copies = cmbCopies.Text.ObjToInt();
            param.MachineID = txtjitaihao.Text.ObjToInt();
            File.WriteAllText(Application.StartupPath+"//Setting.json", JsonConvert.SerializeObject(param));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PrintLabel(PrintStyle.Design, new JuanHaoTable());
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var rolls = table1.DataSource as List<JuanHaoTable>;
            if (table1.SelectedIndex >= 0)
            {
                PrintLabel(PrintStyle.Print, rolls[table1.SelectedIndex-1 ]);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (ShowMessage.ShowAskMessagebox(this, "您确定要删除当前选中的细码吗？") == DialogResult.OK)
            {
                var rolls = table1.DataSource as List<JuanHaoTable>;
                if (table1.SelectedIndex >= 0)
                {
                    dbContext.dbcontext.Deleteable(rolls[table1.SelectedIndex - 1]).ExecuteCommand();
                    var roll=rolls[table1.SelectedIndex-1];
                    dbContext.dbcontext.Deleteable<ChiDianTable >().Where (x=>x.JuanHao ==roll.JuanHao ).ExecuteCommand();
                }
                LoadRolls();
            }
            CalFinishNums();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            try
            {
                var fm = new FabricSelectFrm();
                fm.ShowDialog();
                if (fm.selectdb != null)
                {
                    orderDetailTable = fm.selectdb;
                    txtpingming.Text = fm.selectdb.sampleName;
                    txtOrdernum.Text = fm.selectdb.OrderNum;
                    txtKuanhao.Text = fm.selectdb.Kuanhao;
                    txtguama.Text = "100";
                    cmbDanwei.Text = fm.selectdb.danwei;
                    txtmenfu.Text = string.Empty;
                    txtyanse.Text = fm.selectdb.color;
                    txtganghao.Text = string.Empty;
                    txtBianhao.Text = fm.selectdb.sampleNum;
                    var orderTable = dbContext.dbcontext.Queryable<OrderTable>().First(x => x.OrderNum == fm.selectdb.OrderNum);
                    txtHetonghao.Text = orderTable.ContractNum;
                    txtCustomColor.Text = fm.selectdb.CustomerColorNum;
                    txtCustomFricename.Text = fm.selectdb.CustomerPingMing;
                    txtmenfu.Text = fm.selectdb.width;
                    txtorderNums.Text = fm.selectdb.Num.ToString();
                    labelyaoqiu.Text = orderTable.Packing;
                    cmbCopies.Text = orderTable.ShippingMarkCopies.ToString();
                    txtkezhong.Text = fm.selectdb.weight;
                    if (!string.IsNullOrEmpty(orderTable.ShippingMark))
                    {
                        cmbLabels.Text = orderTable.ShippingMark;
                    }
                    chkchengjian.Checked = true;
                }
                else 
                {
                    orderDetailTable=new OrderDetailTable ();
                    orderTable=new OrderTable ();
                }
                CalFinishNums();
            }
            catch (Exception ex) 
            {
                ShowMessage.ShowErrorMessagebox(this,"选择布料的时候发生了错误"+ex.Message );
            }
        }

        private void txtLength_Click(object sender, EventArgs e)
        {
            txtLength.SelectAll();
        }
        /// <summary>
        /// 创建疵点名称按钮
        /// </summary>
        private void CreateCidianBtn()
        {
            var cidians = dbContext.dbcontext.Queryable<CiDianNameTable>().ToList();
            foreach (var item in cidians)
            {
                var btn = new UIButton() { Width = 90, Height = 50  };
                btn.Text =item.CiDianName+$"({item.Daihao  })" ;
                btn.Click += Btn_Click;
                uiFlowLayoutPanel1.Controls.Add(btn);
            }
           
        }
        private void Btn_Click(object sender, EventArgs e)
        {
            var btn=sender as UIButton;
            var defect = new ChiDianTable() { ChiDianName = btn.Text.Split('(')[0], WeiZhi = txtLength.Text };
            var fm=new InputDefect() { Defect = defect };   
            fm.ShowDialog();
            Defects.Add(defect);
            table3.DataSource = Defects;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            var defect = table3.DataSource as List<ChiDianTable>;
            if (table3.SelectedIndex > 0)
            {
                defect.RemoveAt(table3.SelectedIndex - 1);
                table3.DataSource = defect;
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            var defect = table3.DataSource as List<ChiDianTable>;
            defect.Clear();
            table3.DataSource = defect;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            var defects = table3.DataSource as List<ChiDianTable>;          
            var fm = new InputDefect() { Defect = defects[table3.SelectedIndex] };
            table3.DataSource = defects;
        }
        private void QueryAll()
        {
            var rolls = dbContext.dbcontext.Queryable<JuanHaoTable>().Where(x => x.GangHao.Contains(input7.Text) && x.OrderNum.Contains(input5.Text) && x.yanse.Contains(input6.Text)).OrderByDescending(x => x.rq).ToList();
            table2.DataSource=rolls;
            label28.Text="合计:"+rolls.Count +"卷"+"     长度："+rolls.Sum(x=>x.biaoqianmishu ).ToString ();
        }
        private void button5_Click(object sender, EventArgs e)
        {
           QueryAll();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (ShowMessage.ShowAskMessagebox(this, "您确定要删除当前选中的细码吗？") == DialogResult.OK)
            {
                var rolls = table2.DataSource as List<JuanHaoTable>;
                if (table2.SelectedIndex >= 0)
                {
                    dbContext.dbcontext.Deleteable(rolls[table2.SelectedIndex - 1]).ExecuteCommand();
                    var roll = rolls[table2.SelectedIndex-1];
                    dbContext.dbcontext.Deleteable<ChiDianTable>().Where(x => x.JuanHao == roll.JuanHao).ExecuteCommand();
                }
                QueryAll();
            }
            CalFinishNums();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            var rolls = table2.DataSource as List<JuanHaoTable>;
            if (table2.SelectedIndex >= 0)
            {
                PrintLabel(PrintStyle.Print, rolls[table2.SelectedIndex - 1]);
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtDengji_Click(object sender, EventArgs e)
        {
            var fm = new SelectClassias();
            fm.ShowDialog();
            txtDengji.Text = fm.Grade;
        }

        private void txtStockname_Click(object sender, EventArgs e)
        {
            var fm=new SelectStockname();
            fm.ShowDialog();
            txtStockname.Text=fm.StockName;
        }

        private void input5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) 
            {
                QueryAll();
            }
        }

        private void txtganghao_TextChanged(object sender, EventArgs e)
        {
            var roll = new JuanHaoTable()
            {
                yanse = txtyanse.Text,
                MaShu = txtguama.Value,
                GangHao = txtganghao.Text,
                SampleName = txtpingming.Text,
                biaoqianmishu = Math.Round(txtLength.Text.ObjToDecimal() / txtguama.Text.ObjToDecimal() * 100) - txtzengsong.Text.ObjToDecimal(),
                PiHao = txtjuanhao.Text.ObjToInt(),
                rq = DateTime.Now,
                JuanHao = CreateBarcode(),
                MachineID = txtjitaihao.Text,
                Danwei = cmbDanwei.Text,
                JiaJian = txtzengsong.Text.ObjToDecimal(),
                Ckmc = txtStockname.Text,
                CustomerPingMing = txtCustomFricename.Text,
                CustomerColorNum = txtCustomColor.Text,
                SampleNum = txtBianhao.Text,
                Hetonghao = txtHetonghao.Text,
                DengJI = txtDengji.Text,
                OrderNum = txtOrdernum.Text,
                state = chkchengjian.Checked ? 0 : 1,
                Kezhong = txtkezhong.Text,
                Menfu = txtmenfu.Text,
                kuanhao = txtKuanhao.Text,
                MiShu = txtLength.Text.ObjToDecimal(),
                CustomerName = orderTable.CustomerName,
                Density = orderDetailTable.Density,
                EnglishName = orderDetailTable.EnglishName,
                SecondaryEncoding = orderDetailTable.SecondaryEncoding,
                Saleman = orderTable.SaleMan,
                Composition = orderDetailTable.Component,
                guige = orderDetailTable.Specifications,
                Huahao = orderDetailTable.Huahao,
                Weight = orderDetailTable.weight.ObjToDecimal(),
            };
         txtjuanhao.Text =   RollHelper.CreatGangJuanhao(roll).ToString ();
        }
    }
}
